/**
 * 路由配置
 */
import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../store/modules/user'

// 路由配置
const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/auth/Login.vue'),
    meta: { requiresAuth: false, hideForAuth: true }
  },
  {
    path: '/register',
    name: 'Register', 
    component: () => import('../views/auth/Register.vue'),
    meta: { requiresAuth: false, hideForAuth: true }
  },
  {
    path: '/forgot-password',
    name: 'ForgotPassword',
    component: () => import('../views/auth/ForgotPassword.vue'),
    meta: { requiresAuth: false, hideForAuth: true }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/ProfilePage.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/preferences',
    name: 'Preferences',
    component: () => import('../views/PreferencesPage.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/main',
    name: 'Main',
    component: () => import('../views/Main.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/user-profile',
    name: 'UserProfile',
    component: () => import('../components/user/ProfileView.vue'),
    meta: { requiresAuth: true }
  },

  {
    path: '/settings',
    name: 'Settings',
    component: () => import('../views/Settings.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/error/NotFound.vue'),
    meta: { requiresAuth: false }
  }
]

// 创建路由器
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由历史记录管理
const routeHistory: string[] = loadRouteHistory()
const MAX_HISTORY_SIZE = 10

// 从localStorage加载路由历史
function loadRouteHistory(): string[] {
  try {
    const saved = localStorage.getItem('routeHistory')
    return saved ? JSON.parse(saved) : []
  } catch {
    return []
  }
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 检查路由是否需要认证
  const requiresAuth = to.meta.requiresAuth
  const hideForAuth = to.meta.hideForAuth
  
  // 记录路由历史（排除重复和特殊路由）
  if (from.path && from.path !== to.path && !to.path.includes('#')) {
    // 避免重复记录
    if (routeHistory[routeHistory.length - 1] !== from.path) {
      routeHistory.push(from.path)
      // 限制历史记录大小
      if (routeHistory.length > MAX_HISTORY_SIZE) {
        routeHistory.shift()
      }
      
      // 保存到localStorage
      localStorage.setItem('routeHistory', JSON.stringify(routeHistory))
    }
  }
  
  // 保存当前有效路由到localStorage
  if (to.path && !['/login', '/register', '/404', '/'].includes(to.path) && !to.path.includes('error')) {
    localStorage.setItem('lastValidRoute', to.path)
  }
  
  // 特殊处理：当从/main跳转到其他页面时，保存Main页面的状态
  if (from.path === '/main' && to.path !== '/main') {
    const mainState = {
      currentView: localStorage.getItem('mainCurrentView') || 'novels',
      selectedNovelId: localStorage.getItem('mainSelectedNovelId'),
      selectedCharacterId: localStorage.getItem('mainSelectedCharacterId')
    }
    localStorage.setItem('mainPageState', JSON.stringify(mainState))
  }
  
  // 如果用户已登录且访问登录/注册页面，重定向到主页面
  if (hideForAuth && userStore.isLoggedIn) {
    next('/main')
    return
  }
  
  // 如果需要认证但用户未登录，重定向到登录页
  if (requiresAuth && !userStore.isLoggedIn) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return
  }
  
  next()
})

// 获取最后一个有效路由
const getLastValidRoute = (): string => {
  // 过滤掉登录、注册、404等页面
  const validRoutes = routeHistory.filter(route => 
    !['/login', '/register', '/404', '/'].includes(route) &&
    !route.includes('error')
  )
  
  // 如果有有效历史，返回最后一个
  if (validRoutes.length > 0) {
    return validRoutes[validRoutes.length - 1]
  }
  
  // 否则返回首页
  return '/'
}

// 导出路由历史管理函数
export const getRouteHistory = () => [...routeHistory]
export const clearRouteHistory = () => routeHistory.length = 0
export { getLastValidRoute }

export default router 